package com.sunmouse.toollib.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.Button;


import com.sunmouse.toollib.R;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Kvin on 2017/6/23.
 */
public class VerifyView extends Button {
    public final int DEFAULT_LIMIT = 60;
    private int limit;
    private String mPreTxt;


    private Handler mHandler;
    private Timer mTimer;
    private boolean isCounting;
    private int countLimit;

    public VerifyView(Context context) {
        super(context);
        init();
    }

    public VerifyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
        TypedArray mTa = context.obtainStyledAttributes(attrs, R.styleable.VerifyView);
        this.countLimit = this.limit = mTa.getInteger(R.styleable.VerifyView_vvLimit, DEFAULT_LIMIT);
        mTa.recycle();
        this.mPreTxt = getText().toString();
        setPadding(0,0,0,0);
        resetUI();
    }

    public VerifyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }


    /**
     * init
     *
     * @param
     */
    private void init() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                setText(msg.what + "s");
                if (msg.what == 0) {
                    isCounting = false;
                    resetUI();
                }
            }
        };
    }

    /**
     * start count down
     */
    public void startCount() {
        if (mHandler == null) init();
        isCounting = true;
        resetUI();
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(countLimit--);
            }
        }, 0, 1000);

    }


    /**
     * re set UI
     */
    private void resetUI() {
        if (isCounting) {
            this.countLimit = limit;
//            setBackgroundResource(countBackground);
            setEnabled(false);
//            setTextColor(countTxtColor);
            setClickable(false);
        } else {
            setText(mPreTxt);
//            setBackgroundResource(preBackground);
            setEnabled(true);
//            setTextColor(preTxtColor);
            setClickable(true);
            release();
        }
    }


    /**
     * release
     */
    public void release() {
        //release timer
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }

        //release handler
        if (mHandler != null) mHandler = null;
    }

}
